package com.onstar.cn.weight;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;

import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.BitmapUtil;

/**
 * 
* @ClassName: TouchViewLayerImageView 
* @Description: 用于包裹TouchViewLayer的图片容器，负责显示和控制
* @author zengshuai shi
* @date 2015年8月24日 下午5:23:10
 */
public class TouchViewLayerImageView extends ImageView {
	/**
	 * 
	* @ClassName: LayerStatus 
	* @Description: 图层状态
	* @author zengshuai shi
	* @date 2015年8月24日 下午5:24:24
	 */
	public enum LayerStatus {
		NORMAL, // 普通状态，默认为该状态
		DOWN // 按下状态、高亮状态
	}

	/**
	 * 图层闪烁延迟
	 */
	private final long DEFAULT_BLINK_LATENCY = 80;

	/**
	 * 当前图层状态
	 */
	private LayerStatus layerStatus = LayerStatus.NORMAL;
	
	/**
	 * 绘图缓存
	 */
	private Bitmap drawingCache;

	/**
	 * 触控层数据实体
	 */
	private TouchViewLayer touchViewLayer;

	public TouchViewLayerImageView(Context context, TouchViewLayer touchViewLayer) {
		super(context);
		this.touchViewLayer = touchViewLayer;
		// 调整缩放模式
		setScaleType(ScaleType.CENTER_INSIDE);
		setDrawingCacheEnabled(true);

		if (touchViewLayer == null) {
			throw new NullPointerException("touchViewLayer不能为空");
		}

		if (this.touchViewLayer.getDrawableNormal() == null) {
			throw new NullPointerException("drawableNormal不能为空");
		}
		// 设置默认显示图片
		setImageDrawable(this.touchViewLayer.getDrawableNormal());
	}

	public LayerStatus getLayerStatus() {
		return layerStatus;
	}

	private Animation rotateAnimation;

	public void showAnimation() {
		LogManager.getInstance().i("showAnimation");
		rotateAnimation = AnimationUtils.loadAnimation(getContext(), R.anim.weight_autologin_load_animation);
		LinearInterpolator lin = new LinearInterpolator();
		rotateAnimation.setInterpolator(lin);
		startAnimation(rotateAnimation);
	}

	public void stopAnimation() {
		if (rotateAnimation != null) {
			rotateAnimation.reset();
			clearAnimation();
			rotateAnimation.cancel();
			rotateAnimation = null;
			this.setVisibility(View.GONE);
			setImageDrawable(null);
		}
	}

	/**
	 * 
	* @Title: setLayerStatus 
	* @Description: 切换当前显示层的状态
	* @param @param layerStatus    设定文件 
	* @return void    返回类型 
	* @throws
	 */
	public void setLayerStatus(LayerStatus layerStatus) {
		this.layerStatus = layerStatus;
		BitmapUtil.recycleImageView(this);
		if (this.layerStatus == LayerStatus.NORMAL) {
			setImageDrawable(touchViewLayer.getDrawableNormal());
		} else if (this.layerStatus == LayerStatus.DOWN) {
			Drawable drawableDown = touchViewLayer.getDrawableDown();
			// 按下效果图片可能不存在
			if (drawableDown == null) {
				setImageDrawable(null);
				return;
			}

			setImageDrawable(drawableDown);
		}

		if (drawingCache != null && !drawingCache.isRecycled()) {
			drawingCache.recycle();
			drawingCache = null;
		}
	}

	/**
	 * 
	* @Title: getLayerName 
	* @Description: 得到层名称
	* @param @return    设定文件 
	* @return String    返回类型 
	* @throws
	 */
	public String getLayerName() {
		return touchViewLayer.getLayerName();
	}

	/**
	 * 
	* @Title: blink 
	* @Description: 图层闪烁<br>仅在图层有两种及以上状态图片时有效
	* @param     设定文件 
	* @return void    返回类型 
	* @throws
	 */
	public void blink() {

		new Thread(new Runnable() {

			@Override
			public void run() {
				post(new Runnable() {

					@Override
					public void run() {
						setLayerStatus(LayerStatus.DOWN);
						invalidate();
					}
				});

				synchronized (this) {
					try {
						wait(DEFAULT_BLINK_LATENCY);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

				post(new Runnable() {

					@Override
					public void run() {
						setLayerStatus(LayerStatus.NORMAL);
						invalidate();
					}
				});
			}
		}).start();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// 不需要处理move事件
		if (event.getAction() == MotionEvent.ACTION_MOVE) { 
			return super.onTouchEvent(event);
		}

		// 本层不可触控
		if (!touchViewLayer.isClickable()) { 
			return super.onTouchEvent(event);
		}
		int x = (int) event.getX();
		int y = (int) event.getY();
		if (drawingCache == null) {
			try {
				drawingCache = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_4444);
			} catch (java.lang.OutOfMemoryError e) {
				drawingCache = null;
				e.printStackTrace();
			} catch (Exception e1) {
				e1.printStackTrace();
				drawingCache = null;
			}
		}
		if (drawingCache == null) {
			return super.onTouchEvent(event);
		}

		Canvas drawingCacheCanvas = new Canvas(drawingCache);
		// 只绘制点击区域那一小块
		drawingCacheCanvas.clipRect(x, y, x + 1, y + 1); 
		draw(drawingCacheCanvas);

		int action = event.getAction();
		// 对抬起事件的相应写在对颜色判断之前是因为可能抬起的时候指针落到空白区域
		if (action == MotionEvent.ACTION_UP) { 
			setLayerStatus(LayerStatus.NORMAL);
			if (touchViewLayer.getOnClickListener() != null) {
				touchViewLayer.getOnClickListener().onClick(this);
			}
			return true;
		}
		int color = drawingCache.getPixel(x, y);
		// 如果颜色等于遮罩色则不响应事件
		if (color == touchViewLayer.getMaskColor()) { 
			setLayerStatus(LayerStatus.NORMAL);
			return super.onTouchEvent(event);
		}

		if (action == MotionEvent.ACTION_DOWN) {
			setLayerStatus(LayerStatus.DOWN);
		} else {
			return false;
		}

		return true;
	}
}
